/*
 * Author  : Leo <lipf160627@163.com>
 * Created : 2025-7-27
 * Desc    : ASR-PRO driver using USART
 */

#pragma once

#include <array>
#include <cstddef>
#include <stdint.h>

#include "driver/gpio.h"
#include "driver/uart.h"

// Include protocol here
// Request : 0xAA 0x55 cmd
// Response: 0xAA 0x55 cmd, result [0: success, 1: fail]
// CMDs (ASR -> ESP32):
//  0x01: 前进
//  0x02: 后退
//  0x03: 左转
//  0x04: 右转
//  0x05: 刹车
//  0x10: 顺时针旋转
//  0x11: 逆时针旋转
//  0x20: 打开前车灯
//  0x21: 关闭前车灯
//  0x22: 打开后车灯
//  0x23: 关闭后车灯
//  0x80: 打招呼
// CMDs (ESP32 -> ASR):
//  0xA0: 前方障碍物

#define ASRPRO_CMD_FORWARD              0x01
#define ASRPRO_CMD_BACK                 0x02
#define ASRPRO_CMD_TURN_LEFT            0x03
#define ASRPRO_CMD_TURN_RIGHT           0x04
#define ASRPRO_CMD_STOP                 0x05
#define ASRPRO_CMD_CLOCKWISE            0x10
#define ASRPRO_CMD_ANTICLOCKWISE        0x11
#define ASRPRO_CMD_OPEN_FRONT_LIGHT     0x20
#define ASRPRO_CMD_CLOSE_FRONT_LIGHT    0x21
#define ASRPRO_CMD_OPEN_BACK_LIGHT      0x22
#define ASRPRO_CMD_CLOSE_BACK_LIGHT     0x23
#define ASRPRO_CMD_HELLO                0x80
#define ASRPRO_CMD_OBSTACLE_AHEAD       0xA0
#define ASRPRO_CMD_ACK                  0xE0

class Asrpro {
public:
    Asrpro(uart_port_t uartNum, gpio_num_t pinTx, gpio_num_t pinRx, int baudRate);

    int sendData(const uint8_t* data, size_t len);
    int recvData(uint8_t* buffer, uint32_t bufferLen);    // 目前只支持阻塞

    uint8_t recvCmd();
    bool sendAck(bool success);
    bool sendCmd(uint8_t cmd);

private:
    uart_port_t m_uartNum;
    gpio_num_t  m_pinTx;
    gpio_num_t  m_pinRx;
    int         m_baudRate;

    std::array<uint8_t, 4> m_sendBuf;
    std::array<uint8_t, 3> m_recvBuf;

    void init();
};
